package com.central.apps.handler.project;

import com.central.app.common.base.BaseHandler;
import com.central.app.service.HandlerService;
import com.central.apps.common.constant.BizConstant;
import com.central.apps.service.TableService;
import com.central.bizcommon.model.flow.FlowNode;
import com.central.bizcommon.model.flow.FlowOpinion;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 处理预算结转业务逻辑
 *
 * @author lidachao
 * @date 2023/5/17
 */
@Component
@Slf4j
public class ProjectBudgetCarryOverHandler extends BaseHandler {
    @Autowired
    private HandlerService handlerService;
    @Autowired
    private TableService tableService;

    @Override
    public void beforSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
        if (isUpdate && "gq_pbcarryover".equals(objName)) {
            Integer id = MapUtils.getInteger(data, "id");
            // 查询变更信息
            Map<String, Object> map = handlerService.findOneBySql("select proid, year, pbiid from gq_pbcarryover where id = " + id);
            Integer newProId = MapUtils.getInteger(data, "proid");
            Integer proId = MapUtils.getInteger(map, "proid");
            String newYear = MapUtils.getString(data, "year");
            String year = MapUtils.getString(map, "year");
            Integer newPbiId = MapUtils.getInteger(data, "pbiid");
            Integer pbiId = MapUtils.getInteger(map, "pbiid");

            if (!newProId.equals(proId) || !newYear.equals(year) || !newPbiId.equals(pbiId)) {
                // 删除结转明细信息
                handlerService.updateBySql("delete from gq_pbcosurplus where pbcoid = " + id);
            }
        }
    }

    @Override
    public void afterSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
        // 查询并保存任务信息到任务变更明细
        if ("gq_pbcarryover".equals(objName)) {
            Integer id = MapUtils.getInteger(data, "id");

            List<Map<String, Object>> list = handlerService.findBySql("select id from gq_pbcosurplus where pbcoid = " + id);

            if (CollectionUtils.isEmpty(list)) {
                Integer proId = MapUtils.getInteger(data, "proid");
                String year = MapUtils.getString(data, "year");
                String subjectNo = MapUtils.getString(data, "subjectno");
                String tableName = "";

                // 查询年度预算信息
                StringBuilder sql = new StringBuilder();
                sql.append("select * from ");
                if (BizConstant.PUBLIC_SUBJECT_NO.equals(subjectNo)) {
                    Integer pbiId = MapUtils.getInteger(data, "pbiid");
                    tableName = "gq_ppbudget";
                    sql.append(tableName).append(" where status = '执行中' and parentid in (select id from gq_probugdetcfg where parentid = 0) and proid = ").append(proId).append(" and year = '").append(year).append("' and pbiid = ").append(pbiId);
                } else {
                    tableName = "gq_probudget";
                    sql.append(tableName).append(" where status = '执行中' and pbiid > 0 and proid = ").append(proId).append(" and year = '").append(year).append("'");
                }

                list = handlerService.findBySql(sql.toString());

                if (CollectionUtils.isNotEmpty(list)) {
                    List<Map<String, Object>> insertList = new ArrayList<>();
                    BigDecimal surplusAmt = BigDecimal.ZERO;

                    Map<String, List<String>> convertMap = new HashMap<>();
                    convertMap.computeIfAbsent("id", key -> new ArrayList<>()).add("pbid");

                    for (Map<String, Object> map : list) {
                        Map<String, Object> addMap = tableService.convertMap(tableName, "gq_pbcosurplus", map, convertMap, null);
                        // 手工赋值信息
                        addMap.put("pbcoid", id);
                        insertList.add(addMap);

                        String usefulAmt = MapUtils.getString(map, "usefulamt");
                        BigDecimal usefulAmtDec = new BigDecimal(usefulAmt);

                        surplusAmt = surplusAmt.add(usefulAmtDec);
                    }

                    if (CollectionUtils.isNotEmpty(insertList)) {
                        // 批量插入结转明细信息
                        handlerService.batchInsert(app, "gq_pbcosurplus", insertList);

                        // 更新结转总金额
                        handlerService.updateBySql("update gq_pbcarryover set carryoveramt = " + surplusAmt + " where id = " + id);
                    }
                }
            }
        }
    }

    @Override
    public String beforeExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op) throws Exception {
        Map<String, Object> map = op.getVariables();
        if ("capture".equals(flowNode.getId())) {
            List<Map<String, Object>> list = handlerService.findBySql("select * from gq_pbcosurplus where pbcoid = " + id);
            if (CollectionUtils.isEmpty(list)) {
                return "结转明细不存在, 不能进行结转!";
            }
        }

        if("complete".equals(flowNode.getId()) && op.isFlag()) {
            Integer proId = MapUtils.getInteger(map, "proid");
            String year = MapUtils.getString(map, "year");
            String subjectNo = MapUtils.getString(map, "subjectno");
            String tableName = "gq_probudget";
            if (BizConstant.PUBLIC_SUBJECT_NO.equals(subjectNo)) {
                tableName = "gq_ppbudget";
            }

            handlerService.updateBySql("update " + tableName + " set status = '已结转', surplusamt = usefulamt, usefulamt = 0 where proid = " + proId + " and year = '" + year + "'");
        }
        return null;
    }
}
